package com.etnet.streamserver.view;

import com.etnet.streamserver.util.XmlUtil;
import com.etnet.streamserver.view.client.ClientManager;
import com.etnet.streamserver.view.client.ConnManager;
import com.etnet.streamserver.view.common.ViewFieldMapping;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.dom4j.DocumentException;

public class Configure implements ServletContextListener {
    private static Logger log = Logger.getLogger(Configure.class.getName());
    private static final String CONFIG_NAME = "config.properties";
    private static final String LOG4J_NAME = "log4j.properties";
    private static final int DEFAULT_FORWARD_TIMEOUT = 10;
    private static String loginURL = "http://192.168.1.205/HttpServer/LoginServlet";
    private static int forwardTimeout = 10;

    private static String user = "test27";
    private static String pwd = "test27";
    private static String ss_ip = "192.168.1.203";
    private static String ss_port = "9876";

    private static int SEQ = 1;

    public static String getUser() {
        return user;
    }

    public static void setUser(String user) {
        user = user;
    }

    public static String getPwd() {
        return pwd;
    }

    public static void setPwd(String pwd) {
        pwd = pwd;
    }

    public static String getSs_ip() {
        return ss_ip;
    }

    public static void setSs_ip(String ssIp) {
        ss_ip = ssIp;
    }

    public static String getSs_port() {
        return ss_port;
    }

    public static void setSs_port(String ssPort) {
        ss_port = ssPort;
    }

    public static void setLoginURL(String loginURL) {
        loginURL = loginURL;
    }

    public static synchronized int getSeq() {
        return SEQ++;
    }

    public static String getToken() {
        String token = "";
        try {
            String fullurl = loginURL + "?uid=" + user + "&pwd=" + pwd;
            URL url = new URL(fullurl);
            URLConnection conn = url.openConnection();
            byte[] buf = new byte[1024];
            InputStream is = conn.getInputStream();
            StringBuffer buffer = new StringBuffer();
            while (is.read(buf) > 0) {
                buffer.append(new String(buf, "UTF-8").trim());
            }
            String[] strs = buffer.toString().split("\n");
            if (strs.length >= 2) {
                token = strs[1];
            }
            is.close();
        } catch (IOException localIOException) {
        }

        return token;
    }

    public static String getLoginURL() {
        return loginURL;
    }

    public static int getForwardTimeout() {
        return forwardTimeout;
    }

    public void contextInitialized(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext();
        String log4jfile = servletContext.getInitParameter("log4j-init-file");
        initLog4jConfig(servletContext.getRealPath(log4jfile));
        log.info("--------------------------------------------------");
        log.info("Stream Server Viewer  Version: 0.1.0");
        log.info("--------------------------------------------------");
        String configfile = servletContext.getInitParameter("server-config-file");
        String fieldmapfile = servletContext.getInitParameter("server-fieldmap-file");
        initConfig(servletContext.getRealPath(configfile));
        initFieldMapping(servletContext.getRealPath(fieldmapfile));
//        ConnManager connManager = ConnManager.getInstance();
//        connManager.start(ss_ip, ss_port);
        ClientManager clientManager = ClientManager.getInstance();
        clientManager.setServerIP(ss_ip);
        clientManager.setServerPort(ss_port);
        clientManager.start();
    }

    private void initFieldMapping(String fieldmapfile) {
        try {
            ViewFieldMapping.getInstance().loadData(XmlUtil.getXMLRoot(fieldmapfile));
        } catch (DocumentException e) {
            log.error("init fieldmap field fail." + e.getMessage(), e);
        }
    }

    private void initConfig(String configfile) {
        FileInputStream fis = null;
        Properties prop = new Properties();
        try {
            fis = new FileInputStream(configfile);
            prop.load(fis);
            loginURL = prop.get("app.token.url").toString();
            user = prop.get("app.username").toString();
            pwd = prop.get("app.passward").toString();
            ss_ip = prop.getProperty("app.streamserver.ip");
            ss_port = prop.getProperty("app.streamserver.port");
            log.info("loginURL=" + loginURL + ",user=" + user + ",pwd=" + pwd);
            log.info("connection StreamServer:[ip=" + ss_ip + ",port=" + ss_port + "]");
            log.info("config file is successfully loaded");
        } catch (Exception e) {
            log.error("init config fail." + e.getMessage(), e);
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                log.error("close input stream error for config file" + e.getMessage(), e);
            }
        }
    }

    private void initLog4jConfig(String log4jfile) {
        FileInputStream fis = null;
        Properties prop = new Properties();
        try {
            fis = new FileInputStream(log4jfile);
            prop.load(fis);
            PropertyConfigurator.configure(prop);
            log.info("Log4j configuration file is successfully loaded");
        } catch (Exception e) {
            log.error("init log4j fail." + e.getMessage(), e);
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                log.error("close input stream error for log4j file" + e.getMessage(), e);
            }
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
    }
}